package com.whiteape.book.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AlertDialog;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.whiteape.book.R;
import com.whiteape.book.common.RxEvent;
import com.whiteape.book.common.WaConstants;
import com.whiteape.book.contract.MediaCollectionContract;
import com.whiteape.book.core.manager.MediaStorageManager;
import com.whiteape.book.core.manager.ReadSettingManager;
import com.whiteape.book.core.manager.WebMediaManager;
import com.whiteape.book.model.bo.CollectionMediaWrapper;
import com.whiteape.book.model.bo.MediaGroupBo;
import com.whiteape.book.model.dto.CollectionMediaBean;
import com.whiteape.book.model.dto.CollectionMediaGroupBean;
import com.whiteape.book.model.type.MediaType;
import com.whiteape.book.model.type.RVLayoutType;
import com.whiteape.book.presenter.MediaCollectionPresenter;
import com.whiteape.book.ui.activity.BookReadActivity;
import com.whiteape.book.ui.activity.ComicReadActivity;
import com.whiteape.book.ui.activity.MainActivity;
import com.whiteape.book.ui.activity.MediaGroupActivity;
import com.whiteape.book.ui.adapter.MediaCollectionChildGridAdapter;
import com.whiteape.book.ui.adapter.MediaCollectionChildListAdapter;
import com.whiteape.book.ui.base.BaseRVMVPFragment;
import com.whiteape.book.utils.RxUtils;
import com.whiteape.book.utils.StringUtils;
import com.whiteape.book.utils.ToastUtils;
import com.whiteape.book.widget.RefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import butterknife.BindView;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MediaCollectionChildFragment extends BaseRVMVPFragment<MediaCollectionContract.Presenter, CollectionMediaWrapper>
        implements MediaCollectionContract.View {

    private MediaCollectionChildListAdapter listAdapter;
    private MediaCollectionChildGridAdapter gridAdapter;
    private Executor executor = Executors.newFixedThreadPool(WaConstants.FIX_THREAD_NUM);
    private Scheduler scheduler = Schedulers.from(executor);

    private List<CollectionMediaWrapper> data = new ArrayList<>();
    private static final String MEDIA_TYPE = "media_type";
    private int mediaType = MediaType.MEDIA_TYPE_NOVEL;

    @BindView(R.id.refresh_layout_loading)
    RefreshLayout refreshLayout;

    public static MediaCollectionChildFragment newInstance(int mediaType) {
        Bundle args = new Bundle();
        args.putInt(MEDIA_TYPE, mediaType);
        MediaCollectionChildFragment fragment = new MediaCollectionChildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public MediaCollectionChildFragment() {
    }

    @Override
    protected boolean setBatchDeleteEnabled() {
        return true;
    }

    @Override
    protected List<BaseQuickAdapter<CollectionMediaWrapper, BaseViewHolder>> setAdapter() {
        listAdapter = new MediaCollectionChildListAdapter(data);
        gridAdapter = new MediaCollectionChildGridAdapter(data);

        listAdapter.setLayoutType(RVLayoutType.LIST);
        gridAdapter.setLayoutType(RVLayoutType.GRID);

        listAdapter.setSelectedList(mSelectedList);
        gridAdapter.setSelectedList(mSelectedList);

        List<BaseQuickAdapter<CollectionMediaWrapper, BaseViewHolder>> adapterList = new ArrayList<>();
        adapterList.add(listAdapter);
        adapterList.add(gridAdapter);

        return adapterList;
    }

    @Override
    protected boolean initListOrGrid() {
        return ReadSettingManager.getInstance().getListOrGrid(mediaType);
    }

    @Override
    protected void moveItems(List<CollectionMediaWrapper> itemList) {
        super.moveItems(itemList);
        List<CollectionMediaGroupBean> groups = MediaStorageManager.getInstance().getMediaGroupList();
        int groupNum = groups.size();
        String[] groupNameArr = new String[groupNum + 1];
        Set<String> groupNameSet = new HashSet<>();
        for (int i = 0; i < groupNum; i++) {
            groupNameArr[i] = groups.get(i).getName();
            groupNameSet.add(groups.get(i).getName());
        }
        groupNameArr[groupNum] = " + 添加分组";
        //移动分组
        new AlertDialog.Builder(getContext())
                .setTitle(R.string.wa_common_move_to_group)
                .setItems(groupNameArr, ((dialog, which) -> {
                    if (which == groupNum) {
                        //最后一个是 添加分组
                        final View view = getLayoutInflater().inflate(R.layout.view_alert_dialog_edittext, null);
                        final EditText editText = (EditText) view.findViewById(R.id.editText);
                        new AlertDialog.Builder(getContext())
                                .setTitle(R.string.wa_common_new_group)
                                .setView(view)
                                .setPositiveButton(R.string.wa_common_sure, (dialog1, which1) -> {
                                    String name = editText.getText().toString();
                                    if (StringUtils.isEmpty(name)) {
                                        ToastUtils.show("分组名字不可为空!");
                                        return;
                                    }
                                    if (groupNameSet.contains(name.trim())){
                                        ToastUtils.show("该分组已存在！");
                                        return;
                                    }
                                    MediaStorageManager.getInstance().saveMediaGroup(name);
                                    dialog1.dismiss();
                                    moveItems(itemList);

                                })
                                .setNegativeButton(R.string.wa_common_cancel, ((dialog1, which1) -> {
                                    dialog1.dismiss();

                                })).show();
                    }else{
                        List<CollectionMediaBean> beanList = new ArrayList<>();
                        for(CollectionMediaWrapper bean : itemList){
                            bean.getMediaBean().setGroup(groupNameArr[which]);
                            beanList.add(bean.getMediaBean());
                        }
                        mSelectedList.clear();
                        MediaStorageManager.getInstance().batchSaveCollectionMediaBaseInfo(beanList);
                        RxBus.get().post(RxEvent.MEDIA_COLLECTION_REFRESH, new CollectionMediaBean());
                    }

                })).show();


    }

    @Override
    protected void deleteItems(List<CollectionMediaWrapper> itemList) {
        List<CollectionMediaBean> beanList = new ArrayList<>();
        for(CollectionMediaWrapper bean : itemList){
            beanList.add(bean.getMediaBean());
        }
        new AlertDialog.Builder(getContext())
                .setTitle(R.string.wa_common_tip)
                .setMessage(getString(R.string.delete_media_msg, itemList.size()))
                .setPositiveButton(R.string.wa_common_sure, (dialog, which) -> {

                    addDisposable(MediaStorageManager.getInstance().deleteCollMediaListInRx(beanList)
                            .compose(RxUtils::toSimpleSingle).subscribe(v -> {
                                data.removeAll(itemList);
                                listAdapter.notifyDataSetChanged();
                                gridAdapter.notifyDataSetChanged();
//                    refresh();
                                mSelectedList.clear();
                                innerRefresh(false);
                            }));
                })
                .setNegativeButton(R.string.wa_common_cancel, ((dialog, which) -> {
                    dialog.dismiss();

                })).show();
    }

    @Override
    protected boolean setAdapterModeSwitchEnabled() {
        return true;
    }

    @Override
    protected boolean setMoveEnabled() {
        return true;
    }

    @Override
    protected boolean showTotal() {
        return true;
    }

    @Override
    protected void onItemChildClickListener(BaseQuickAdapter adapter, View view, int position) {
        if (view.getId() == R.id.iv_select) {
//            ToastUtils.show("ccccclick");
        }
    }


    @Override
    protected void onItemClickListener(BaseQuickAdapter adapter, View view, int position) {

        if (getContext() == null) {
            return;
        }
        CollectionMediaWrapper wrapper = data.get(position);
        if (mediaType == MediaType.MEDIA_TYPE_NOVEL) {
            if(wrapper.isGroup()){
                //打开分组
                openGroup(wrapper);
            }else {
                BookReadActivity.startActivity(getContext(), wrapper.getMediaBean(), true, -1);
            }
        } else if (mediaType == MediaType.MEDIA_TYPE_COMIC) {
            if(wrapper.isGroup()){
                //打开分组
                openGroup(wrapper);
            }else {
                ComicReadActivity.startActivity(getContext(), wrapper.getMediaBean(), null, true, null);
            }
        }
    }

    private void openGroup(CollectionMediaWrapper wrapper){
        try {
            Intent intent = new Intent(getActivity(), MediaGroupActivity.class);
            intent.putExtra("group_name", wrapper.getMediaGroupBo().getName());
            intent.putExtra("media_type", wrapper.getMediaGroupBo().getMediaBeanList().get(0).getMediaType());
            intent.putParcelableArrayListExtra("media_list", wrapper.getMediaGroupBo().getMediaBeanList());
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onSelectStateChanged(boolean selectStateEnable) {
        if (selectStateEnable) {
            Objects.requireNonNull((MainActivity) getActivity()).hideTab();
        } else {
            Objects.requireNonNull((MainActivity) getActivity()).showTab();
        }
        listAdapter.setSelectedStateEnable(selectStateEnable);
        gridAdapter.setSelectedStateEnable(selectStateEnable);
    }

    @Override
    protected void onListOrGridStateChanged(boolean isList) {
        ReadSettingManager.getInstance().setListOrGrid(mediaType, isList);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mediaType = getArguments().getInt(MEDIA_TYPE, MediaType.MEDIA_TYPE_NOVEL);
        }
        super.initData(savedInstanceState);
    }

    public int getMediaType() {
        if (getArguments() != null) {
            mediaType = getArguments().getInt(MEDIA_TYPE, MediaType.MEDIA_TYPE_NOVEL);
        }
        return mediaType;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
//        String type = MediaType.getName(mediaType);
//        refreshLayout.setEmptyText("还没有" + type + "哦,点击右上角搜索下吧~");
        refreshLayout.showLoading();
        setEmptyView(R.layout.layout_empty_media);

    }
    //    @Override
//    protected void initView(Bundle savedInstanceState) {
//        super.initView(savedInstanceState);
//        rvContent.setLayoutManager(new LinearLayoutManager(getContext()));
//        if (getContext() != null) {
//            rvContent.addItemDecoration(new DividerItemDecoration(getContext()));
//        }
//        listAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
    //加载动画不仅仅是第一次
//        listAdapter.isFirstOnly(false);
    //下拉刷新
//        listAdapter.setUpFetchEnable(true);
//        rvContent.setAdapter(listAdapter);

//    }

//    @Override
//    protected void initEvent() {
//        super.initEvent();
//        listAdapter.setOnItemClickListener((adapter, view, position) -> {
//
//        });
//    }

    private void refreshCatalog() {
        // media list
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                CollectionMediaBean bean = data.get(i).getMediaBean();
                final int x = i;

                if (bean == null || bean.getIfLocal()) {
                    continue;
                }
                listAdapter.addRefreshingMedia(bean.getId());
                gridAdapter.addRefreshingMedia(bean.getId());
                Disposable disposable = WebMediaManager.getInstance().getCatalog(bean.getSiteSourceBean(), bean)
//                        .subscribeOn()
                        //.compose(RxUtils::toSimpleSingle)
                        .subscribeOn(scheduler)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mediaChapterBeanList -> {
                            MediaStorageManager.getInstance()
                                    .saveMediaChapters(mediaChapterBeanList);
                            listAdapter.removeRefreshingMedia(bean.getId());
                            gridAdapter.removeRefreshingMedia(bean.getId());
                            listAdapter.notifyItemChanged(x);
                            gridAdapter.notifyItemChanged(x);
                        }, throwable -> {
                            listAdapter.removeRefreshingMedia(bean.getId());
                            gridAdapter.removeRefreshingMedia(bean.getId());
                            listAdapter.notifyItemChanged(x);
                            gridAdapter.notifyItemChanged(x);
                        });
                addDisposable(disposable);
            }
        }

    }

    @Override
    protected void refreshDone() {
        innerRefresh(true);
    }

    private void innerRefresh(boolean refreshCatalog) {
        refresh();
        if (refreshCatalog) {
            refreshCatalog();
        }
    }

    @Override
    public void finishRefresh(List<CollectionMediaBean> collectionMediaBeans, boolean forceRefreshCatalog) {
        data.clear();

        List<CollectionMediaWrapper> wrapperList = new ArrayList<>();
        Map<String, ArrayList<CollectionMediaBean>> groupMap = new HashMap<>();
        for(CollectionMediaBean bean : collectionMediaBeans){
            String groupName = bean.getGroup();
            if(!StringUtils.isEmpty(groupName)){
                if(!groupMap.containsKey(groupName)){
                    ArrayList<CollectionMediaBean> beanList = new ArrayList<>();
                    groupMap.put(groupName, beanList);
                }
                groupMap.get(groupName).add(bean);
            }else{
                CollectionMediaWrapper wrapper = new CollectionMediaWrapper();
                wrapper.setMediaBean(bean);
                wrapper.setGroup(false);
                wrapperList.add(wrapper);
            }
        }
        for(String groupName : groupMap.keySet()){
            CollectionMediaWrapper wrapper = new CollectionMediaWrapper();
            wrapper.setGroup(true);
            MediaGroupBo mediaGroupBo = new MediaGroupBo();
            mediaGroupBo.setMediaBeanList(groupMap.get(groupName));
            mediaGroupBo.setName(groupName);
            wrapper.setMediaGroupBo(mediaGroupBo);
            wrapperList.add(wrapper);
        }

        data.addAll(wrapperList);
//        afterRefreshingData();
//        listAdapter.notifyDataSetChanged();
//        gridAdapter.notifyDataSetChanged();
//        refresh();
        //理论上 应该是每次重新打开app才刷新
        innerRefresh(forceRefreshCatalog);
        refreshLayout.showFinish();
        if (getView() != null) {
            getView().requestLayout();
        }
    }


    @Override
    protected MediaCollectionPresenter bindPresenter() {
        return new MediaCollectionPresenter();
    }

    @Override
    public void showError() {
        refreshLayout.showError();

    }

    @Override
    public void complete() {

    }

//    @Override
//    protected int getContentId() {
//        return R.layout.fragment_collection_child;
//    }

    @Override
    protected void startLogic() {
        super.startLogic();

        mRecyclerView.setVisibility(View.INVISIBLE);
        mPresenter.refreshCollectionMedia(mediaType, ReadSettingManager.getInstance().getCollMediaAutoUpdateCatalog());
    }


    @Subscribe(thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxEvent.MEDIA_COLLECTION_ADD),
                    @Tag(RxEvent.MEDIA_COLLECTION_REMOVE),
                    @Tag(RxEvent.MEDIA_COLLECTION_REFRESH)})
    public void onCollectionStateChanged(CollectionMediaBean collectionMediaBean) {
        mPresenter.refreshCollectionMedia(mediaType, false);
    }


}
